document.write("<script type='text/javascript' src='qrcode.min.js'></script>");

// 获取 qrcode 的 URL
const fetchQrCodeUrl =
    "https://bling-dev-openapi.percent.cn/api/open/user/qrcode/generate?appId=20210519152249264891973603";

// 二维码地址
const qrCodeBaseUrl =
    "https://bling-dev-openapi.percent.cn/api/open/user/qrcode/commit?appId=20210519152249264891973603&redirectUri=http%3A%2F%2Flowcode-dev.percent.cn%2Forgselect";

// 获取 login tmp code 地址
const loginTmpCodeUrl =
    "https://bling-dev-openapi.percent.cn/api/open/user/qrcode/state?appId=20210519152249264891973603&redirectUri=http%3A%2F%2Flowcode-dev.percent.cn%2Forgselect";

const origin = "https://bling-openapi.percent.cn";

let intervalId;

// 处理 IE 可能不支持自定义事件问题
(function () {
    if (typeof window.CustomEvent === "function") {
        // 如果不是IE
        return false;
    }

    var CustomEvent = function (event, params) {
        params = params || {
            bubbles: false,
            cancelable: false,
            detail: undefined,
        };
        var evt = document.createEvent("CustomEvent");
        evt.initCustomEvent(
            event,
            params.bubbles,
            params.cancelable,
            params.detail
        );
        return evt;
    };

    CustomEvent.prototype = window.Event.prototype;

    window.CustomEvent = CustomEvent;
})();

let dollogin = {
    /**
     *
     * @param {
     *   id: "login_container", // 这里需要你在自己的页面定义一个HTML标签并设置id，例如: <div id="login_container"></div>或<span id="login_container"></span>
     *   goto: "", // 请参考注释里的方式
     *   style: "border:none;background-color:#FFFFFF;",
     *   width : 365,
     *   height: 400
     * }
     */
    ready: function (params) {
        // 获取 qrCode 地址
        postData(fetchQrCodeUrl, {})
            .then((result) => {
                if (result.code === 0) {
                    const qrCode = result.data.qrCode;

                    // 生成二维码
                    generateQrCode(params, qrCode);

                    // 轮询二维码
                    intervalId = setInterval(getQrCodeStatus, 1000, qrCode);
                }
            })
            .catch((err) => {
                console.log("Catch exception: ", err);
            });
    },
};

function getQrCodeStatus(qrCode) {
    const url = loginTmpCodeUrl + `&qrCode=${qrCode}`;

    postData(url, {})
        .then((result) => {
            if (result.code === 0) {
                const loginTmpCode = result.data.tmpCode;

                // 发送事件，业务获取 loginTmpCode
                const event = new CustomEvent("message", {
                    detail: {
                        data: loginTmpCode,
                        origin: origin,
                    },
                });

                // 分发事件，业务代码捕获
                window.dispatchEvent(event);

                // 清除定时器
                clearInterval(intervalId);
            }
        })
        .catch((err) => {
            console.log("Catch exception: ", err);
            clearInterval(intervalId);
        });
}

function generateQrCode(params, qrCode) {
    // 生成二维码
    const id = params.id;
    const width = params.width;
    const height = params.height;

    var qrCodeObj = new QRCode(document.getElementById(id), {
        text: qrCodeBaseUrl + `&qrCode=${qrCode}`,
        width: width,
        height: height,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.Q,
    });
}

function postData(url, data) {
    // Default options are marked with *
    return fetch(url, {
        body: JSON.stringify(data), // must match 'Content-Type' header
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, same-origin, *omit
        headers: {
            "user-agent": "Mozilla/4.0 MDN Example",
            "content-type": "application/json",
        },
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // *client, no-referrer
    }).then((response) => response.json()); // 輸出成 json
}
